package designpatterns.utils;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class ScanClassUtil {

    /**
     * 扫描bean,封装为beanDefinition
     * @param packagePath : 包路径
     * @return 包路径下面的class对象
     */
    public static List<Class> scan(String packagePath) {
        ClassLoader classLoader = ScanClassUtil.class.getClassLoader();
        String sysPath = packagePath.replace(".", "//");
        URL url = classLoader.getResource(sysPath);
        // 扫描文件
        File file = new File(url.getFile());
        return scanFile(file, classLoader);
    }

    /**
     * 扫描文件,使用类加载器将文件加载为class
     * @param file
     * @param classLoader
     */
    public static List<Class> scanFile(File file,ClassLoader classLoader) {
        List<Class> classList = new ArrayList<>();
        if (file.isDirectory()) {
            for (File f : file.listFiles()) {
                if (f.isDirectory()) {
                    // 是文件夹继续进入文件夹扫描
                    scanFile(f,classLoader);
                    continue;
                }

                // 使用类加载器加载文件
                String absolutePath = f.getAbsolutePath();
                String sysClassPath = absolutePath.substring(absolutePath.indexOf("designpatterns"), absolutePath.indexOf(".class"));
                String classPath = sysClassPath.replace("\\", ".");
                try {
                    Class<?> clazz = classLoader.loadClass(classPath);
                    classList.add(clazz);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }

            }
        }
        return classList;
    }
}
